package services

import (
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/infrastructure/caches"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"go.uber.org/dig"
)

type SettingService struct {
	l           v1log.ILog
	dao         interfaces.ItfSettingDao
	cacheByName *caches.CacheFacade[string, string]
}

func NewSettingService(di *dig.Container, l v1log.ILog, settingDao interfaces.ItfSettingDao, cache caches.ItfCache) *SettingService {
	ctr := &SettingService{
		l:           l,
		dao:         settingDao,
		cacheByName: caches.NewCacheFacade[string, string](cache),
	}

	ctr.cacheByName.WithValueFunc(func(k string) string {
		s, err := settingDao.Get(k)
		if err != nil {
			return ""
		}
		return s
	}).WithKeyPrefix("settings_")

	return ctr
}

func (s *SettingService) Set(key, value string) error {
	return s.dao.Set(key, value)
}

func (s *SettingService) Get(key string) (string, error) {
	return s.dao.Get(key)
}

func (s *SettingService) SetMulti(data map[string]string) error {
	return s.dao.SetMulti(data)
}

func (s *SettingService) GetMulti(keys ...string) (map[string]string, error) {
	return s.dao.GetMulti(keys...)
}

func (s *SettingService) GetFromCache(name string) (string, error) {
	key := s.CacheKeyForOne(name)
	v, err := s.cacheByName.Get(key)
	if err != nil {
		return "", err
	}
	return v, err
}

func (s *SettingService) GetMultiFromCache(names ...string) (map[string]string, error) {
	var data = make(map[string]string)
	var err error
	for _, key := range names {
		data[key], err = s.GetFromCache(key)
		if err != nil {
			return data, err
		}
	}
	return data, nil
}

func (s *SettingService) CacheKeyForOne(key string) string {
	return "setting_" + key
}
